﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using System.IO;

namespace NAstAp
{
    public partial class ConfigEdit : Form
    {
        private static EventHandler itemMenuClickEvent;
        XmlDocument doc;
        public ConfigEdit()
        {
            InitializeComponent();
        }

        private void ConfigEdit_Load(object sender, EventArgs e)
        {
            doc = LoadConfig();
            foreach (XmlElement elm in doc.SelectNodes("/Config/NetworkConfiguration"))
            {
                cmbConfigurations.Items.Add(elm.GetAttribute("name"));
            }
            itemMenuClickEvent += new EventHandler(OnItemMenuClick);
        }

        private static XmlDocument LoadConfig()
        {
            string config = FindConfigDocument();
            XmlDocument doc = new XmlDocument();
            doc.Load(config);
            return doc;
        }

        public static string FindConfigDocument()
        {
            string inAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            inAppData = Path.Combine(inAppData, "NetworkAwareAssistant\\NetworkAwareAssistant.xml");

            if (File.Exists(inAppData))
                return inAppData;

            inAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            inAppData = Path.Combine(inAppData, "NetworkAwareAssistant\\NetworkAwareAssistant.xml");

            if (File.Exists(inAppData))
                return inAppData;


            if (File.Exists("NetworkAwareAssistant.xml"))
                return "NetworkAwareAssistant.xml";

            return null;
        }

        private void cmbConfigurations_SelectedValueChanged(object sender, EventArgs e)
        {
            treeTest.Nodes.Clear();
            treeTest.Nodes.Add(doc.SelectSingleNode("/Config/NetworkConfiguration[@name='" + cmbConfigurations.Items[cmbConfigurations.SelectedIndex].ToString() + "']/Tests").Name);
            TreeNode node = new TreeNode();
            node = treeTest.Nodes[0];
            ContextMenuStrip menu = new ContextMenuStrip();
            menu.Items.Add("Add");
            node.ContextMenuStrip = menu;
            AddNode(doc.SelectSingleNode("/Config/NetworkConfiguration[@name='" + cmbConfigurations.Items[cmbConfigurations.SelectedIndex].ToString() + "']/Tests"), node);
            treeTest.ExpandAll();
            treeNetlets.Nodes.Clear();
            treeNetlets.Nodes.Add(doc.SelectSingleNode("/Config/NetworkConfiguration[@name='" + cmbConfigurations.Items[cmbConfigurations.SelectedIndex].ToString() + "']/Netlets").Name);
            node = treeNetlets.Nodes[0];
            AddNode(doc.SelectSingleNode("/Config/NetworkConfiguration[@name='" + cmbConfigurations.Items[cmbConfigurations.SelectedIndex].ToString() + "']/Netlets"), node);
            treeNetlets.ExpandAll();
        }

        private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList nodeList;
            ContextMenuStrip menu = new ContextMenuStrip();
            menu.Items.Add("Change",null,itemMenuClickEvent);
            menu.Items.Add("Remove",null,itemMenuClickEvent);
            int i;

            // Loop through the XML nodes until the leaf is reached.
            // Add the nodes to the TreeView during the looping process.
            if (inXmlNode.HasChildNodes)
            {
                nodeList = inXmlNode.ChildNodes;
                for (i = 0; i <= nodeList.Count - 1; i++)
                {
                    xNode = inXmlNode.ChildNodes[i];
                    inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = inTreeNode.Nodes[i];
                    tNode.ContextMenuStrip = menu;
                    AddNode(xNode, tNode);
                }
            }
            else
            {
                // Here you need to pull the data from the XmlNode based on the
                // type of node, whether attribute values are required, and so forth.
                inTreeNode.Text = (inXmlNode.OuterXml).Trim();
            }
        }

        private void OnItemMenuClick(object sender, EventArgs args)
        {
            ToolStripItem item = (ToolStripItem)sender;
        }

        private void treeTest_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Label != null)
            {
                if (e.Label.Length > 0)
                {
                    if (e.Label.IndexOfAny(new char[] { '@', '.', ',', '!' }) == -1)
                    {
                        // Stop editing without canceling the label change.
                        e.Node.EndEdit(false);
                    }
                    else
                    {
                        /* Cancel the label edit action, inform the user, and 
                           place the node in edit mode again. */
                        e.CancelEdit = true;
                        MessageBox.Show("Invalid tree node label.\n" +
                           "The invalid characters are: '@','.', ',', '!'",
                           "Node Label Edit");
                        e.Node.BeginEdit();
                    }
                }
                else
                {
                    /* Cancel the label edit action, inform the user, and 
                       place the node in edit mode again. */
                    e.CancelEdit = true;
                    MessageBox.Show("Invalid tree node label.\nThe label cannot be blank",
                       "Node Label Edit");
                    e.Node.BeginEdit();
                }
                this.treeTest.LabelEdit = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            IPConfig config = new IPConfig();
            config.ShowDialog();
        }
    }
}
